package cn.edu.bzu.manager.computer.controller;

import cn.edu.bzu.manager.computer.entity.AdminUser;
import cn.edu.bzu.manager.computer.service.AdminService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 * 返回类型均为JSON类型
 *
 * @author 1923111015董寺卓
 * @since 1.8
 */

@RestController
@AllArgsConstructor
@RequestMapping("/admin")
public class AdminController {

    private final AdminService adminService;

    /**
     * POST
     * 管理员登录验证方法
     * 使用前端提交的name与password使用Service验证正确性
     *
     * @param requestMap 请求内容K-V表
     * @return 验证成功后返回大于0的ID和adminRole名，否则返回null
     */
    @PostMapping("/validate")
    public Map<String, ?> validateAdmin(@RequestBody Map<String, String> requestMap,
                                        HttpSession httpSession) {
        AdminUser user = adminService.
                findAdminUserByNameAndPassword(requestMap.get("name"), requestMap.get("password"));
        if (user != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("adminRole", user.getAdminRole().getName());
            httpSession.setAttribute("userId", user.getId());
            return map;
        }
        return null;
    }

    /**
     * GET
     *
     * @return 所有的用户的ID和名字
     */
    @GetMapping("/all")
    public List<?> showAllAdminIdAndName() {
        return adminService.findAllAdminIdAndName();
    }

}
